package com.niguang.work.api.weChatTemplate;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.niguang.common.constant.ResultCode;
import com.niguang.common.pojo.Result;
import com.niguang.common.util.ApiTokenUtils;
import com.niguang.common.util.HttpClientUtil;
import com.niguang.work.api.entity.WechatUser;
import com.niguang.work.api.service.WechatUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpUserService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wechat/")
@Slf4j
public class WeChatParams {

    @Value("${wechat.miniMass.appId}")
    private String miniAppId;

    @Value("${wechat.miniMass.secret}")
    private String miniSecret;


    @Value("${wechat.mp.appId}")
    private String mqAppId;

    @Value("${wechat.mp.secret}")
    private String mqSecret;

    @Resource
    private WxMpUserService wxMpUserService;

    @Resource
    private ApiTokenUtils apiTokenUtils;

    @Resource
    private WechatUserService wechatUserService;

    /**
     * 通过jscode获取用户信息
     */
    private static final String snsUrl = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";


    /**
     * 获取微信用户信息
     *
     * @param jsCode
     * @return
     */
    @GetMapping("getOppenId")
    public Result getOppenId(@NotNull String jsCode) {
        try {
            String url = String.format(snsUrl, miniAppId, miniSecret, jsCode);
            log.info("获取微信用户信息请求接口：{}", url);
            String params = HttpClientUtil.get(url);
            log.info("获取微信用户信息：{}", params);
            if (StringUtils.isBlank(params)) {
                return Result.build(ResultCode.FORBIDDEN, "openId获取失败！");
            }
            Map map = JSONObject.parseObject(params, Map.class);
            if (map.containsKey("errcode")) {
                return Result.build(ResultCode.FAILED, "openId获取失败", map.get("errmsg"));
            }
            return Result.build(ResultCode.SUCCESS, "openId获取成功", map);
        } catch (Exception e) {
            log.error("微信openId获取失败！", e);
        }
        return Result.failed();
    }

    /**
     * 检查用户是否绑定微信公众号
     *
     * @return
     */
    @GetMapping("checkBind")
    public Result checkBind() {
        try {
            String unionId = apiTokenUtils.getUnionId();
            if (StringUtils.isBlank(unionId)) {
                return Result.build(ResultCode.PARAM_ERROR, "unionId不能为空！");
            }
            EntityWrapper<WechatUser> entityWrapper = new EntityWrapper<>();
            entityWrapper.eq(WechatUser.UNION_ID, unionId);
            List<WechatUser> userList = wechatUserService.selectList(entityWrapper);
            if (CollectionUtils.isEmpty(userList)) {
                return Result.build(ResultCode.UNAUTHORIZED, "微信号未绑定用户！");
            }
            WechatUser wechatUser = userList.get(0);
            WxMpUser wxMpUser = wxMpUserService.userInfo(wechatUser.getOpenId());
            log.info("微信用户信息查询数据：{}", wxMpUser);
            if (ObjectUtils.isEmpty(wxMpUser)) {
                return Result.build(ResultCode.SUCCESS, "微信用户信息获取成功", false);
            }
            return Result.build(ResultCode.SUCCESS, "微信用户信息获取成功", wxMpUser.getSubscribe());
        } catch (Exception e) {
            log.error("微信用户信息查询失败：{}", e);
        }
        return Result.failed();
    }


}
